package com.yqw.onlineDocs.manager.websocket;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.yqw.onlineDocs.model.entity.Document;
import com.yqw.onlineDocs.model.entity.DocumentUser;
import com.yqw.onlineDocs.model.entity.User;
import com.yqw.onlineDocs.model.enums.DocumentPermissionEnum;
import com.yqw.onlineDocs.service.DocumentService;
import com.yqw.onlineDocs.service.DocumentUserService;
import com.yqw.onlineDocs.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * WebSocket拦截器
 * 创建拦截器用于权限校验和用户信息传递
 */
@Component
@Slf4j
public class DocumentWsHandshakeInterceptor implements HandshakeInterceptor {

  @Resource
  private UserService userService;

  @Resource
  private DocumentService documentService;

  @Resource
  private DocumentUserService documentUserService;

  @Override
  public boolean beforeHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response,
      @NotNull WebSocketHandler wsHandler, @NotNull Map<String, Object> attributes) {
    if (request instanceof ServletServerHttpRequest) {
      HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
      // 获取请求参数
      String documentIdStr = servletRequest.getParameter("documentId");
      if (StrUtil.isBlank(documentIdStr)) {
        log.error("缺少文档ID参数，拒绝握手");
        return false;
      }
      User loginUser = userService.getLoginUser(servletRequest);
      if (ObjUtil.isEmpty(loginUser)) {
        log.error("用户未登录，拒绝握手");
        return false;
      }
      // 校验用户是否有该文档的权限
      Long documentId = Long.valueOf(documentIdStr);
      Document document = documentService.getById(documentId);
      if (document == null) {
        log.error("文档不存在，拒绝握手");
        return false;
      }
      // 查询用户在该文档中的权限
      DocumentUser documentUser = documentUserService.getDocumentUserByDocumentIdAndUserId(documentId,
          loginUser.getId());
      if (documentUser == null) {
        log.error("用户没有该文档的权限，拒绝握手");
        return false;
      }
      // 检查是否有编辑权限
      String permission = documentUser.getPermission();
      if (!DocumentPermissionEnum.ADMIN.getValue().equals(permission) &&
          !DocumentPermissionEnum.EDITOR.getValue().equals(permission)) {
        log.error("用户没有文档编辑权限，拒绝握手");
        return false;
      }
      // 设置 attributes
      attributes.put("user", loginUser);
      attributes.put("userId", loginUser.getId());
      attributes.put("documentId", documentId);
      attributes.put("permission", permission);
    }
    return true;
  }

  @Override
  public void afterHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response,
      @NotNull WebSocketHandler wsHandler, Exception exception) {
    // 握手后的处理，通常为空
  }
}